package com.huangd.platform.modules.job.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huangd.platform.common.utils.*;
import com.huangd.platform.common.utils.cron.CronUtil;
import com.huangd.platform.common.utils.cron.TaskScheduleModel;
import com.huangd.platform.modules.job.dao.ScheduleJobDao;
import com.huangd.platform.modules.job.entity.ScheduleJobEntity;
import com.huangd.platform.modules.job.service.ScheduleJobService;
import com.huangd.platform.modules.job.utils.ScheduleUtils;
import org.apache.commons.lang.StringUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

@Service("scheduleJobService")
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobDao, ScheduleJobEntity> implements ScheduleJobService {
	@Resource
    private Scheduler scheduler;
	
	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init(){
		List<ScheduleJobEntity> scheduleJobList = this.list();
		for(ScheduleJobEntity scheduleJob : scheduleJobList){
			CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            //如果不存在，则创建
            if(cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            }else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
		}
	}

	@Override
	public R<ScheduleJobEntity> queryPage(Map<String, Object> params) {
		String beanName = (String)params.get("beanName");

		IPage<ScheduleJobEntity> page = this.page(
			new Query<ScheduleJobEntity>().getPage(params),
			new QueryWrapper <ScheduleJobEntity>().like(StringUtils.isNotBlank(beanName),"bean_name", beanName)
		);
		PageUtils pageUtils = new PageUtils(page);
		List<ScheduleJobEntity> list = (List<ScheduleJobEntity>) pageUtils.getList();
		for (ScheduleJobEntity entity : list) {
			String json = entity.getParams();
			Map map = JSONUtil.toBean(json, Map.class);
			Object interval = map.get("intervalTime");
			if (interval != null) {
				Integer intervalTime = (Integer) interval;
				entity.setIntervalTime(intervalTime);
			}
			TaskScheduleModel taskScheduleModel = getTaskScheduleModel(entity);
			String taskRunTime = CronUtil.createDescription(taskScheduleModel);
			entity.setTaskRunTime(taskRunTime);
		}

		return R.ok(pageUtils);
	}

	private TaskScheduleModel getTaskScheduleModel(ScheduleJobEntity entity) {
		Integer loadTime = entity.getLoadTime();
		String time = entity.getTime();
		DateTime dateTime = DateUtil.parse(time);
		int hour = dateTime.hour(true);
		int minute = dateTime.minute();
		int second = dateTime.second();
		TaskScheduleModel taskScheduleModel = new TaskScheduleModel();
		if (loadTime == 1) {
			taskScheduleModel.setJobType(1);
		} else if (loadTime == 2) {
			Integer week = entity.getWeek();
			taskScheduleModel.setJobType(3);
			taskScheduleModel.setDayOfWeeks(new Integer[] {week});
		} else if (loadTime == 3) {
			Integer date = entity.getDate();
			taskScheduleModel.setJobType(2);
			taskScheduleModel.setDayOfMonths(new Integer[] {date});
		}
		taskScheduleModel.setHour(hour);
		taskScheduleModel.setMinute(minute);
		taskScheduleModel.setSecond(second);
		return taskScheduleModel;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveJob(ScheduleJobEntity scheduleJob) {
		scheduleJob.setCreateTime(new Date());
		scheduleJob.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
		setJobData(scheduleJob);
		this.save(scheduleJob);
        
        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
    }

	private void setJobData(ScheduleJobEntity scheduleJob) {
		// 保存数据加载时间长度参数
		Integer intervalTime = scheduleJob.getIntervalTime();
		if (intervalTime != null) {
			Map<String, Object> map = null ;
			String json = scheduleJob.getParams();
			if (StringUtils.isBlank(json)) {
				map = new HashMap<>();
			} else {
				map = JSONUtil.toBean(json, Map.class);
			}
			switch (intervalTime) {
				case 1:
					map.put("beginTime", DateUtil.yesterday().toDateStr());
					map.put("endTime", DateUtil.yesterday().toDateStr());
					break;
				case 2:
					map.put("beginTime", DateUtil.lastWeek().toDateStr());
					map.put("endTime", DateUtils.addDays(DateUtils.string2Date(DateUtil.beginOfWeek(new Date()).toDateStr(), DateUtils.PATTERN_DATE), -1));
					break;
				case 3:
					map.put("beginTime", DateUtil.lastMonth().toDateStr());
					map.put("endTime", DateUtils.addDays(DateUtils.string2Date(DateUtil.beginOfMonth(new Date()).toDateStr(), DateUtils.PATTERN_DATE), -1));
					break;
				case 4:
					map.put("beginTime", DateUtils.date2String(new Date(), DateUtils.PATTERN_DATE));
					map.put("endTime", DateUtils.date2String(new Date(), DateUtils.PATTERN_DATE));
					break;
			}
			map.put("intervalTime", intervalTime);
			String s = JSONUtil.toJsonPrettyStr(map);
			scheduleJob.setParams(s);
		}
		// 生成 cron表达式
		TaskScheduleModel taskScheduleModel = getTaskScheduleModel(scheduleJob);
		String cron = CronUtil.createCronExpression(taskScheduleModel);
		scheduleJob.setCronExpression(cron);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(ScheduleJobEntity scheduleJob) {
		setJobData(scheduleJob);
        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
        this.updateById(scheduleJob);
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		ScheduleUtils.deleteScheduleJob(scheduler, jobId);
    	}
    	
    	//删除数据
    	this.removeByIds(Arrays.asList(jobIds));
	}

	@Override
    public int updateBatch(Long[] jobIds, int status){
    	Map<String, Object> map = new HashMap<>(2);
    	map.put("list", Arrays.asList(jobIds));
    	map.put("status", status);
    	return baseMapper.updateBatch(map);
    }
    
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void run(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		ScheduleUtils.run(scheduler, this.getById(jobId));
    	}
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
        for(Long jobId : jobIds){
    		ScheduleUtils.pauseJob(scheduler, jobId);
    	}
        
    	updateBatch(jobIds, Constant.ScheduleStatus.PAUSE.getValue());
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void resume(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		ScheduleUtils.resumeJob(scheduler, jobId);
    	}

    	updateBatch(jobIds, Constant.ScheduleStatus.NORMAL.getValue());
    }
}
